#include "TcpListener.h"
#include "iostream"
#include "../myrpc/myrpc.pb.h"


const int DEFAULT_BACKLOG = 128;

namespace myrpc
{
	namespace mynet
	{	
		
		int TcpListener::Init(){

			loop_ = uvw::Loop::getDefault();
			tcphandler_ = loop_->resource<uvw::TcpHandle>();
			return 0;
		
		}

		int TcpListener::Listen(std::string  ip, int port)
		{	
			ip_ = ip;
			port_ = port;
			tcphandler_->on<uvw::ErrorEvent>([](const uvw::ErrorEvent & error, uvw::TcpHandle & handle)
			{
				std::cout << error.what() << std::endl;
			});

			tcphandler_->on<uvw::CloseEvent>([](const uvw::CloseEvent &, uvw::TcpHandle & handle)
			{
				std::cout << "close" << std::endl;
			});

			tcphandler_->on<uvw::ListenEvent>([=](const uvw::ListenEvent & event, uvw::TcpHandle & handle)
			{	
				auto  session = Session::Create(loop_);
				tcphandler_->accept(*(session->GetHandler()));
				session->Start();
				_ConnectReach(session);
			});

			tcphandler_->bind(ip_, port_);
			tcphandler_->listen();
			loop_->run();
			
			return 0;
		}

		int TcpListener::Close()
		{	
			tcphandler_->close();
			return 0;
		}

		void TcpListener::SetConnectReach(std::function<void(std::shared_ptr<myrpc::mynet::Session>)> f)
		{
			_ConnectReach = f;
		}


	}
}